<?php
/* --------------------------------------------------------------
   FetchShopConfigValueAction.php 2024-05-23
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2024 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

declare(strict_types=1);

namespace Gambio\Api\Modules\ShopConfig\App\Actions;

use Gambio\Api\Modules\ShopConfig\App\ShopConfigApiRequestValidator;
use Gambio\Core\Application\Http\Request;
use Gambio\Core\Application\Http\Response;
use Gambio\Core\Configuration\Services\ConfigurationService;

/**
 * Class FetchShopConfigValueAction
 *
 * @package Gambio\Api\Modules\ShopConfig\App\Actions
 */
class FetchShopConfigValueAction
{
    
    protected ConfigurationService          $configurationService;
    protected ShopConfigApiRequestValidator $requestValidator;
    
    
    /**
     * FetchShopConfigValueAction constructor.
     *
     * @param ConfigurationService          $configurationService
     * @param ShopConfigApiRequestValidator $requestValidator
     */
    public function __construct(
        ConfigurationService          $configurationService,
        ShopConfigApiRequestValidator $requestValidator,
    ) {
        $this->configurationService = $configurationService;
        $this->requestValidator     = $requestValidator;
    }
    
    
    /**
     * @param Request  $request
     * @param Response $response
     * @param array    $args
     *
     * @return Response
     */
    public function __invoke(Request $request, Response $response, array $args): Response
    {
        $errors = $this->requestValidator->validateGetParams($args);
        if (count($errors) > 0) {
            return $response->withStatus(404)->withJson(['errors' => $errors]);
        }
        $prefix = $this->requestValidator->getConfigPrefix();
        $key    = $args[$this->requestValidator->getKeyParamName()];
        $config = $this->configurationService->find($prefix . $key);
        
        return $response->withJson(["data" => $config?->value()]);
    }
    
}